package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    //获取文件上传地址
    @Value("${minio.endpointUrl}")
    private String endpointUrl;
    //获取上传文件账号
    @Value("${minio.accessKey}")
    private String accessKey;
    //获取上传文件密码
    @Value("${minio.secretKey}")
    private String secretKey;
    //获取文件上传桶的名称
    @Value("${minio.bucketName}")
    private String bucketName;


    @PostMapping("fileUpload")
    public Result fileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        //创建文件路径
        String url = "";
        //构建MinioClient对象
        MinioClient minioClient = MinioClient.builder().endpoint(endpointUrl).credentials(accessKey, secretKey).build();
        //判断minio的桶是否存在
        boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (b) {
            System.out.println("Bucket already exists!");
        } else {
            //创建一个名为asiatrip的存储桶名称,用于存储图片的zip文件
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //创建一个上传文件名称，名称不能重复
        String fileName = System.currentTimeMillis() + UUID.randomUUID().toString();
        //使用putObject上传一个文件到桶中
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(
                        file.getInputStream(), file.getSize(), -1
                ).contentType(file.getContentType()).build());

        url = endpointUrl + "/" + bucketName + "/" + fileName;

        return Result.ok(url);
    }


}
